﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ProtoBuf.Meta;
using SyncCore.Sync;
using SyncCore.Sync.Helpers;
using SyncCore.Sync.Models;
using SyncCore.Sync.Utils;
using SyncDemo.Sync.Models;
using SyncDemo.Sync.Utils;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows.Input;

namespace MessageDebugWindow
{
    internal partial class CommandItem : ObservableObject
    {
        [ObservableProperty]
        private string _name;

        [ObservableProperty]
        private ICommand _command;
    }

    internal partial class MainViewModel : ObservableObject
    {
        [ObservableProperty]
        private string _hexCode;

        [ObservableProperty]
        private string _readableCode;

        [ObservableProperty]
        private ObservableCollection<CommandItem> _commandItems = new ObservableCollection<CommandItem>();

        private RuntimeTypeModel _typeModel;
        private byte[] _buffer;
        public MainViewModel()
        {
            _typeModel = TypeModelHelper.CreateMessagePackTypeModel();
            _buffer = new byte[Peer.BufferSize];

            var messagePackCommandItem = new CommandItem()
            {
                Command = new RelayCommand(SendBoardcast),
                Name = "boardcast"
            };

            CommandItems.Add(messagePackCommandItem);
        }

        private string GetHexCode(byte[] buffer)
        {
            var sb = new StringBuilder();
            sb.Append("[ ");
            foreach (var value in buffer)
            {
                sb.Append(value.ToString("X2"));
                sb.Append(" ");
            }
            sb.Append("]");
            return sb.ToString();
        }

        private byte[] FromHexCode(string hexCode)
        {
            if (string.IsNullOrWhiteSpace(hexCode)) return null;
            var tokens = hexCode.Split();

            var bytes = new List<byte>();

            for (int i = 1; i < tokens.Length - 1; i++)
            {
                var hex = tokens[i];
                var value = System.Convert.FromHexString(hex)[0];
                bytes.Add(value);
            }

            return bytes.ToArray();
        }

        [RelayCommand]
        private void Convert()
        {

        }

        private void SendBoardcast()
        {
            var boardcastMessagePack = new MessagePack() { Type = MessageType.Boardcast };
            var ms = new MemoryStream(_buffer);
            _typeModel.SerializeWithLengthPrefix(ms, boardcastMessagePack, typeof(MessagePack), ProtoBuf.PrefixStyle.Base128, 1);
            ms.Close();
            ms.Dispose();

            HexCode = GetHexCode(_buffer);
        }
    }
}
